<template>
    <div>
        <!-- 添加成员模态框 -->
        <section>
            <el-dialog :title="addUserForm.title" :visible.sync="isShow.add" width="600px" :close-on-click-modal="false">
                <el-form :model="addUserForm" style="padding:0 40px;" ref="addUserForm">
                    <el-form-item label="姓名" :label-width="formLabelWidth" prop="user_name" :rules="filter_rules({required:true})">
                        <el-input @blur.prevent="checkFormBlur('user_name')" v-model.trim="addUserForm.user_name" placeholder="请输入姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="部门名称" :label-width="formLabelWidth">
                        <el-tag v-for="dept in addUserForm.depts" :key="dept.id" style="margin-right:6px;">{{dept.label}}</el-tag>
                        <el-button size="mini" type="text" icon="iconfont ali-add" circle @click="openDeptModal"></el-button>
                    </el-form-item>
                    <el-form-item label="手机" :label-width="formLabelWidth" prop="phone" :rules="filter_rules({required: true,type: 'mobile'})">
                        <el-input @blur.prevent="checkFormBlur('phone')" v-model.trim="addUserForm.phone" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email" :rules="filter_rules({type:'email'})">
                        <el-input @blur.prevent="checkFormBlur('email')" v-model.trim="addUserForm.email" placeholder="请输入邮箱"></el-input>
                    </el-form-item>
                    <el-form-item label="工号" :label-width="formLabelWidth">
                        <el-input v-model="addUserForm.work_num" placeholder="请输入工号"></el-input>
                    </el-form-item>
                    <el-form-item label="性别" :label-width="formLabelWidth">
                        <el-radio v-model="addUserForm.sex" :label="1">男</el-radio>
                        <el-radio v-model="addUserForm.sex" :label="0">女</el-radio>
                    </el-form-item>
                    <el-form-item label="生日" :label-width="formLabelWidth">
                        <el-date-picker v-model="addUserForm.birthday" value-format="yyyy-MM-dd" type="date" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="入职时间" :label-width="formLabelWidth">
                        <el-date-picker v-model="addUserForm.entry_date" value-format="yyyy-MM-dd" type="date" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="前台可以登陆" :label-width="formLabelWidth">
                        <el-radio v-model="addUserForm.reception_islogin" :label="0">否</el-radio>
                        <el-radio v-model="addUserForm.reception_islogin" :label="1">是</el-radio>
                    </el-form-item>
                    <el-form-item label="后台可以登陆" :label-width="formLabelWidth">
                        <el-radio v-model="addUserForm.backstage_islogin" :label="0">否</el-radio>
                        <el-radio v-model="addUserForm.backstage_islogin" :label="1">是</el-radio>
                    </el-form-item>
                    <el-form-item :label="field.reservefield_name" :label-width="formLabelWidth" v-for="(field,i) in reservefield" :key="field.id">
                        <el-input v-model="cacheFields[i].reservefield_value" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="isShow.add = false">取 消</el-button>
                    <el-button type="primary" :disabled="exist.show" @click="validate('addUserForm')">{{exist.msg}}</el-button>
                </span>
            </el-dialog>
        </section>
        <!-- 部门人员调整部门 -->
        <section>
            <dept-transfer ref="childInit" @closeTransfer="isShow.transfer = false" @getDepts="getDepts(transfer.decide, $event)" :isShow="isShow.transfer"></dept-transfer>
        </section>
    </div>
</template>
<script>
import deptTransfer from './edit_dept_transfer'
import { user_edit, user_checkUser, user_findById } from '@/api/user'
import { dept_findById } from '@/api/group'
import { reservefield_listAll } from '@/api/reservefield'
import { mapGetters } from 'vuex'

export default {
    components: { deptTransfer },
    data() {
        return {
            formLabelWidth: '100px',
            reservefield: [],
            addUserForm: {},
            transfer: {},
            multipleSelection: [],
            isShow: { add: false, dept: false, child: false, transfer: false },
            exist: { show: false, msg: '确 定' }
        }
    },
    computed:{
    ...mapGetters([
      'cacheDept'
    ])
  },
    methods: {
        async checkFormBlur(field) {
            if (!this.addUserForm[field]) {
                return;
            }
            const val = { user_name: '姓名', phone: '手机', email: '邮箱' }
            let params = {company_id: localStorage.getItem('companyId') - 0};
            params[field] = this.addUserForm[field]
            const { data } = await user_checkUser(params);

            if (data.status === 100) {
                if (data.data.exist === 1) {
                    this.exist = { show: true, msg: `${val[field]}已存在！` };
                    this.$message.warning(`${val[field]}已存在！`);
                } else {
                    this.exist = { show: false, msg: '确 定' };
                }
            }
        },
        openDeptModal() {//打开部门模态框 ----添加成员用
            this.$refs.childInit.openTransfer();
            this.isShow.transfer = true;
        },
        async initField() {//初始化备用字段
            let { data } = await reservefield_listAll({ company_id: localStorage.getItem("companyId") });
            if (data.status == 100) {
                this.reservefield = data.data.rows;
                this.initFieldValue();
            }
        },
        initFieldValue() {//初始化备用字段value值
            this.cacheFields = []
            this.reservefield.forEach(item => {
                this.cacheFields.push({ reservefield_id: item.id, reservefield_value: '' })
            })
        },
        validate(e) {
            this.$refs[e].validate((valid) => {
                if (valid) {
                    if (!this.addUserForm.depts || this.addUserForm.depts.length == 0) {
                        this.$message.warning('请选择部门')
                        return;
                    }
                    this.addMember();
                } else {
                    return false;
                }
            });
        },
        getDepts(e, obj) {
            if (obj.length == 0) {
                this.$message.warning('至少要选择一个部门')
                return;
            }
            if (e == 'addMember' || e == 'editMember') {//添加成员||修改
                this.addUserForm.depts = obj
            } else if (e == 'revise') {//调整部门
                this.editMember(obj);
            }
            this.isShow.transfer = false;
        },
        async addMember() {//添加成员||修改
            this.isShow.add = false;
            this.addUserForm.dept_ids = this.addUserForm.depts.map(item => item.id).join();  //this.addUserForm.depts[0].id;
            this.addUserForm.company_id = localStorage.getItem("companyId");
            this.$emit("update:loading", true);
            let decide = this.transfer.decide;
            this.addUserForm.reservefields = JSON.stringify(this.cacheFields);
            let result;
            result = await user_edit(this.addUserForm);
            this.$store.dispatch('FineUsersByDeptId', this.cacheDept.id);//重新加载当前页面成员
            this.$emit("update:loading", false);
            if (result.data.status == 100) {
                this.$message.success(decide == 'addMember' ? '添加成功' : '编辑成功')
            } else {
                this.$message.error(result.data.msg)
            }
        },
        async openPerson(e) {//打开编辑人员信息模态框
            this.loading = true;
            e.title = e.user_name + `(ID:${e.id})`;
            this.addUserForm = e;
            // this.addUserForm.depts = [this.cacheDept];
            await this.findDeptsByStrId(e.dept_ids)
            let { data } = await user_findById({ id: e.id });
            if (data.status == 100) {
                this.cacheFields = []
                data.data.reservefields.forEach((item, i) => {
                    this.cacheFields[i] = item;
                })
            }
            this.loading = false;
            this.isShow.add = true;
            this.transfer.decide = 'editMember';
        },
        async editMember(e) {//人员调整部门调用接口
            this.loading = true
            for (var i = 0; i < this.multipleSelection.length; i++) {
                var element = this.multipleSelection[i];
                let params = { id: element.id, dept_ids: e.map(item => e.id).join() }
                await user_edit(params)
            }
            this.loading = false
            this.$message.success('修改成功')
            this.$store.dispatch('FineUsersByDeptId', this.cacheDept.id);//重新加载当前页面成员
        },
        async findDeptsByStrId(ids) {
            let depts = []
            let arr = ids.split(',');
            for (let i = 0; i < arr.length; i++) {
                let id = arr[i];
                let { data } = await dept_findById({ company_id: localStorage.getItem("companyId"), id: id })
                if (data.status === 100) {
                    depts.push({ ...data.data, label: data.data.dept_name })
                }
            }
            this.addUserForm.depts = depts;
        },
    }
}
</script>
